<template>
  <div class="p-6 space-y-4">
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="作业类型">
              <el-select v-model="filters.type" clearable placeholder="请选择">
                <el-option v-for="t in workTypes" :key="t" :label="t" :value="t" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="计划开始时间">
              <el-date-picker v-model="filters.planStart" type="date" placeholder="选择日期" clearable class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="作业内容">
              <el-input v-model="filters.content" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="作业状态">
              <el-select v-model="filters.status" clearable placeholder="请选择">
                <el-option v-for="s in workStatuses" :key="s" :label="s" :value="s" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="4" class="flex justify-end items-end">
            <el-button type="primary" :loading="queryLoading" @click="onSearch">
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="作业票名称" prop="name" min-width="180" />
          <el-table-column label="作业类型" prop="type" min-width="140" />
          <el-table-column label="作业等级" prop="level" min-width="120" />
          <el-table-column label="作业内容" prop="content" min-width="200" />
          <el-table-column label="作业单位类型" prop="unitType" min-width="140" />
          <el-table-column label="计划开始时间" prop="planStart" min-width="160" />
          <el-table-column label="实际开始时间" prop="actualStart" min-width="160" />
          <el-table-column label="作业状态" width="140" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

interface WorkTicketRow {
  id: number;
  name: string;
  type: string;
  level: string;
  content: string;
  unitType: string;
  planStart: string;
  actualStart: string;
  status: string;
}

const workTypes = ['动火作业', '受限空间作业', '盲板抽堵作业', '临时用电作业', '高处作业', '吊装作业', '动土作业', '断路作业'];

const workStatuses = [
  '待开票审批',
  '取消',
  '待提交',
  '待安全分析',
  '安全分析中',
  '待气体检测',
  '待安全交底',
  '审批中',
  '待作业',
  '作业中',
  '暂停中',
  '待验收',
  '待关闭',
  '作业关闭'
];

const filters = reactive({
  type: '',
  planStart: '' as any,
  content: '',
  status: ''
});

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const allRecords = ref<WorkTicketRow[]>([]);

const statusTagType = (status: string) => {
  const primary = ['审批中', '作业中', '待作业', '待验收'];
  const warning = ['待安全分析', '安全分析中', '待气体检测', '待安全交底', '暂停中'];
  const success = ['作业关闭'];
  const danger = ['取消'];
  if (success.includes(status)) return 'success';
  if (danger.includes(status)) return 'danger';
  if (warning.includes(status)) return 'warning';
  if (primary.includes(status)) return 'primary';
  return 'info';
};

const mockInit = () => {
  const levels = ['一级', '二级', '三级'];
  const contents = ['设备检修焊接', '罐区内清洗', '更换盲板', '临时配电安装', '高处更换阀门', '大型设备吊装', '沟槽开挖', '配电柜断路作业'];
  const unitTypes = ['自有单位', '承包商'];
  const statusList = workStatuses;

  const list: WorkTicketRow[] = [];
  let id = 1;
  const n = 11; // 固定条数
  for (let i = 0; i < n; i++) {
    const type = workTypes[i % workTypes.length];
    const level = levels[i % levels.length];
    const content = contents[i % contents.length];
    const unitType = unitTypes[i % unitTypes.length];
    const status = statusList[i % statusList.length];
    const month = (i % 9) + 1;
    const day = String(5 + (i % 20)).padStart(2, '0');
    const planStart = `2025-${String(month).padStart(2, '0')}-${day} 09:00`;
    const actualStart = `2025-${String(month).padStart(2, '0')}-${day} ${String(9 + (i % 6)).padStart(2, '0')}:30`;
    const name = `${type}票-${content}`;
    list.push({ id: id++, name, type, level, content, unitType, planStart, actualStart, status });
  }
  allRecords.value = list;
};

const tableData = ref<WorkTicketRow[]>([]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const formatDate = (d: any) => {
  if (!d) return '';
  const dt = new Date(d);
  const y = dt.getFullYear();
  const m = String(dt.getMonth() + 1).padStart(2, '0');
  const da = String(dt.getDate()).padStart(2, '0');
  return `${y}-${m}-${da}`;
};

const applyFilter = () => {
  const k = filters.content.trim();
  const p = filters.planStart ? formatDate(filters.planStart) : '';
  return allRecords.value.filter((r) => {
    const matchType = filters.type ? r.type === filters.type : true;
    const matchPlan = p ? r.planStart.startsWith(p) : true;
    const matchContent = k ? r.content.includes(k) || r.name.includes(k) : true;
    const matchStatus = filters.status ? r.status === filters.status : true;
    return matchType && matchPlan && matchContent && matchStatus;
  });
};

const refreshTable = (list: WorkTicketRow[]) => {
  pagination.total = list.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = list.slice(start, start + pagination.pageSize);
};

const fetchList = async (btn = true) => {
  if (btn) queryLoading.value = true;
  tableLoading.value = true;
  try {
    await new Promise((r) => setTimeout(r, 200));
    const filtered = applyFilter();
    refreshTable(filtered);
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};
const onSizeChange = (s: number) => {
  pagination.pageSize = s;
  pagination.currentPage = 1;
  fetchList(false);
};
const onPageChange = (p: number) => {
  pagination.currentPage = p;
  fetchList(false);
};

const onDelete = async (row: WorkTicketRow) => {
  try {
    await ElMessageBox.confirm(`确认删除“${row.name}”？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    tableLoading.value = true;
    await new Promise((r) => setTimeout(r, 200));
    allRecords.value = allRecords.value.filter((x) => x.id !== row.id);
    if ((pagination.currentPage - 1) * pagination.pageSize >= allRecords.value.length && pagination.currentPage > 1) pagination.currentPage -= 1;
    await fetchList(false);
    ElMessage.success('删除成功');
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

onMounted(async () => {
  mockInit();
  await fetchList(false);
});
</script>
